package fun.easycode.webterminal.service.impl;

import fun.easycode.webterminal.common.contract.DynamicOperate;
import fun.easycode.webterminal.common.contract.PageDTO;
import fun.easycode.webterminal.common.contract.R;
import fun.easycode.webterminal.dao.Topology;
import fun.easycode.webterminal.dao.TopologyRepository;
import fun.easycode.webterminal.service.TopologyService;
import fun.easycode.webterminal.service.cmd.TopologyPageQry;
import fun.easycode.webterminal.service.cmd.TopologySaveCmd;
import fun.easycode.webterminal.service.cmd.TopologySaveCmdAssembler;
import fun.easycode.webterminal.service.dto.TopologyDTO;
import fun.easycode.webterminal.service.dto.TopologyDTOAssembler;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class TopologyServiceImpl implements TopologyService {

    @Resource
    private TopologyRepository topologyRepository;

    @Override
    public R<String> delete(String id) {

        topologyRepository.removeById(id);

        return R.message("删除成功");
    }

    @Override
    public R<TopologyDTO> getById(String id) {
        Topology topology = topologyRepository.getById(id);

        if(topology == null){
            return R.error("拓扑不存在");
        }
        return R.success(TopologyDTOAssembler.INSTANCE.to(topology));

    }

    @Override
    public R<PageDTO<TopologyDTO>> page(TopologyPageQry cmd) {

        cmd.validate();

        PageDTO<TopologyDTO> page = DynamicOperate.page(cmd, topologyRepository.getBaseMapper(), TopologyDTOAssembler.INSTANCE::to);

        return R.success(page);
    }

    @Override
    public R<String> save(TopologySaveCmd cmd) {
        cmd.validate();

        Topology topology = TopologySaveCmdAssembler.INSTANCE.to(cmd);

        topologyRepository.saveOrUpdate(topology);

        return R.message("保存成功");
    }
}
